<template>
  <PageLayout full :page-style="pageStyle">
    <!--头部导航-->
    <template #header>
      <HeaderLayout show-back>
        <view></view>
        <view>{{ titleName }}</view>
      </HeaderLayout>
    </template>
    <scroll-view class="container" scroll-y @scrolltolower="loadMoreData">
      <view class="cell" v-for="(data, index) in messageList" :key="index" wx:key="data" @click="jumpToDetail(index)">
        <view class="time">{{ data.sendTimeByDateDesc }} {{ data.sendTimeByTimeDesc }}</view>
        <view class="detail">
          <view class="left">
            <view class="name">{{ data.messageTitle }}</view>
            <view class="des">{{ data.messageContent }}</view>
          </view>
          <image v-if="data.canClick" class="arrow" :src="'/static/ic_right_arrow.png'"></image>
        </view>
      </view>
      <view class="no-more-tips" v-if="!hasMoreData">当前没有更多消息</view>
    </scroll-view>

    <NetworkError :show-flag="noNetwork" />

    <Modal
      :ok-text="$t('Navigator.Loading.Acknowledge.Text')"
      :title="$t('Navigator.Loading.Hint.Text')"
      :visible="loadStore.errorHint"
      @ok="close"
    >
      <text class="comError">{{ loadStore.errorTxt }}</text>
    </Modal>
  </PageLayout>
</template>
<script lang="ts"></script>
<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import NetworkError from '@/common/networkError.vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import type { Message } from '@/api/messageCenter'

import { updateClickLinkStatus } from '@/api/wxuserSignInfo'
import { jumpMP } from '@/utils/mpHelper'
import { choosePath, openArticle } from '@/utils/loading'
import { readMessageByHaid } from '@/api/messageCenter'
import Modal from '@/common/modal.vue'
import { useLoadStore } from '@/store/loading'

import { getApplianceMessageDetailList } from '@/api/messageCenter'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'
import { toTargetMiniProgramTypes } from '@/constants/AppInfo'

let errorHint = ref(false)
let errorTxt = ref('')

const loadStore = useLoadStore()

const messageList = ref<Message[]>([])

const pageStyle = {
  backgroundColor: '#F4F4F4',
}

const pageSize = 10
let currentPage = 1
const hasMoreData = ref(false)
const i18n = useI18n()
let noNetwork = ref(false)
let appliance_type = ''

const titleName = ref('')

let haId = ''
/**
 * 页面加载
 */
onLoad(async (options: any) => {
  let applianceMessageData = JSON.parse(decodeURIComponent(options.applianceMessageData))
  messageList.value = applianceMessageData.list
  titleName.value = applianceMessageData.name
  appliance_type = applianceMessageData.type
  messageList.value.forEach((element) => {
    let options = getUrlParams(element.messageLink)
    let landing_type = parseInt(options.landing_type)
    // 是否可点击判断
    if (
      landing_type === 0 ||
      landing_type === 1 ||
      landing_type === 3 ||
      landing_type === 4 ||
      landing_type === 8 ||
      landing_type === 10
    ) {
      element.canClick = true
    }
  })

  haId = messageList.value[0].haId
  // 获取当前家电下的所有消息
  getMessageDeailList(haId, false)
  // 批量阅读haId对应消息
  let res: any = null
  try {
    res = await readMessageByHaid(haId)
  } catch (error) {
    res = error
  } finally {
    safeTrack(() => {
      trackEvent(
        'read_single_appliance_message',
        {
          successOrNot: res.code == 0,
          error_code: res.code,
          response_msg: res.msg,
        },
        TrackType.BusinesssScene,
        'Home.MessageCenter.Appliance.Select'
      )
    })
  }
})

/**
 * 获取家电下的消息列表数据
 * @param haId
 * @param pullDataFlag 是否是上拉加载
 */
async function getMessageDeailList(haId: string, pullDataFlag: boolean) {
  if (pullDataFlag) {
    currentPage++
  }
  let res = await getApplianceMessageDetailList(haId, currentPage, pageSize)
  if (res.code === 0) {
    hasMoreData.value = res.data.length === pageSize
    if (pullDataFlag) {
      res.data.forEach((element, index) => {
        let options = getUrlParams(element.messageLink)
        let landing_type = parseInt(options.landing_type)
        // 是否可点击判断
        if (
          landing_type === 0 ||
          landing_type === 1 ||
          landing_type === 3 ||
          landing_type === 4 ||
          landing_type === 8 ||
          landing_type === 10
        ) {
          element.canClick = true
        }
        messageList.value.push(element)
      })
    } else {
      messageList.value.splice(0, messageList.value.length)
      messageList.value = res.data
      messageList.value.forEach((element) => {
        let options = getUrlParams(element.messageLink)
        let landing_type = parseInt(options.landing_type)
        // 是否可点击判断
        if (
          landing_type === 0 ||
          landing_type === 1 ||
          landing_type === 3 ||
          landing_type === 4 ||
          landing_type === 8 ||
          landing_type === 10
        ) {
          element.canClick = true
        }
      })
    }
  }
}

/**
 * 上拉加载
 */
function loadMoreData() {
  if (hasMoreData.value) {
    getMessageDeailList(haId, true)
  }
}

/**
 * 关闭
 */
function close() {
  loadStore.errorHint = false
}

/**
 * 到底部刷新接口
 */
onReachBottom(() => {})

/**
 * 处理时间为所需要格式
 * @param dateString
 */

/**
 * 跳转到详情
 */
async function jumpToDetail(index: number) {
  let messageListValue = messageList.value

  const { id, messageLink, canClick } = messageListValue[index]
  safeTrack(() => {
    trackEvent(
      'before_check_message_actionhandler',
      { message_id: id },
      TrackType.ApplianceDetail,
      'Home.MessageCenter.System.Detail.Select'
    )
  })
  if (!canClick) return

  const options = getUrlParams(messageLink)

  uni.showLoading({
    title: i18n.t('APP.Common.Loading.Text'),
    mask: true,
  })

  let res: any = null
  try {
    res = await updateClickLinkStatus(id)
  } catch (error) {
    res = error
  } finally {
    safeTrack(() => {
      trackEvent(
        'check_message_actionhandler',
        { message_id: id, successOrNot: res.code == 0, error_code: res.code, response_msg: res.msg },
        TrackType.ApplianceDetail,
        'Home.MessageCenter.System.Detail.Select'
      )
    })
  }

  uni.hideLoading()

  if (options.landingPage) {
    options.landingPage = decodeURIComponent(options.landingPage)
  }
  // 拼接haId
  if (options.haid && !options.landingPage.includes('haid')) {
    const queryAppendMark = options.landingPage.includes('?') ? '&' : '?'
    options.landingPage = options.landingPage.concat(`${queryAppendMark}haid=${options.haid}`)
  }

  let landing_type = parseInt(options.landing_type)

  // 特殊处理Oven等家电
  const isOtherMPTypes = toTargetMiniProgramTypes.includes(appliance_type)
  if (isOtherMPTypes) {
    landing_type = 0
    options.miniprogram_id = 'wx4a7a485f483fd236'
    if (appliance_type == 'CookProcessor') {
      options.miniprogram_id = 'wxec2dafeacbaf5fb5'
    }
  }

  if (landing_type === 0) {
    let appid = options.miniprogram_id ? options.miniprogram_id : options.appid ? options.appid : ''
    let path = options.landingPage ? options.landingPage : options.path ? options.path : ''
    if (appid) {
      jumpMP(appid, path, {}, 'Home.MessageCenter.MessageDetail.Select.ToOtherPM')
    } else {
      errorHint.value = true
      errorTxt.value = 'appid缺失'
    }
  } else if (options.landing_type == '1') {
    choosePath(options)
  } else if (options.landing_type == '3') {
    openArticle(options.article_id)
  } else if (options.landing_type == '4') {
    let url = `/pages/discovery/recipeDetail/recipeDetail?recipeId=${options.recipe_id}`
    if (options.isDefault == '1') {
      url = `/pages/discovery/recipeDetail_1/recipeDetail?recipeId=${options.recipe_id}`
    } else if (options.isDefault == '2') {
      url = `/pages/discovery/oemRecipeDetail/oemRecipeDetail?recipeId=${options.recipe_id}`
    }
    uni.navigateTo({
      url: url,
    })
  } else if (options.landing_type == '10') {
    choosePath(options)
  } else if (options.landing_type == '8') {
    choosePath(options)
  }
}

/**
 * 获取url路径后的参数
 * @param str
 */
function getUrlParams(str: string) {
  if (!str) {
    // 判断是否传入值
    return {}
  }
  if (typeof str === 'string' && str.split('?').length > 1) {
    // 判断传入值得数据类型
    str = str.replace(str.split('?')[0] + '?', '')
    let arr = str.split('&')
    let obj: Record<string, string> = {}
    for (let i = 0; i < arr.length; i++) {
      let newarr = arr[i].split('=')[0]
      let key = newarr
      let value = arr[i].replace(arr[i].split('=')[0] + '=', '')
      obj[key] = value
    }
    return obj
  } else {
    return {}
  }
}
</script>
<style lang="less">
.unClicked {
  color: #4475d5;
  text-decoration: underline;
}
.beClicked {
  color: #0e6faa;
  text-decoration: underline;
}
.container {
  background-color: #f4f4f4;
  height: 100%;
  box-sizing: border-box;
}

.text {
  font-family: 'PingFang SC';
  font-style: normal;
  font-weight: 600;
  font-size: 26rpx;
  color: #333333;
}

.cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 32rpx 32rpx;
  .time {
    background: #000000;
    opacity: 0.2;
    border-radius: 4rpx;
    font-family: 'PingFang SC';
    font-style: normal;
    font-weight: 400;
    font-size: 24rpx;
    color: #ffffff;
    text-align: center;
    white-space: nowrap;
    padding: 2rpx 8rpx;
  }
  .detail {
    width: 100%;
    background: #ffffff;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    margin-top: 16rpx;
    height: 140rpx;
    .left {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      margin-left: 32rpx;
      .name {
        font-family: 'PingFang SC';
        font-style: normal;
        font-weight: 500;
        font-size: 28rpx;
        color: #333333;
        margin-top: 24rpx;
      }
      .des {
        font-family: 'PingFang SC';
        font-style: normal;
        font-weight: 400;
        font-size: 28rpx;
        color: #333333;
        opacity: 0.6;
        margin-bottom: 24rpx;
      }
    }
    .arrow {
      width: 14rpx;
      height: 24rpx;
      margin-right: 24rpx;
      margin-left: 24rpx;
    }
  }
}

.cell:first-of-type {
  margin-top: 16rpx;
}

.no-more-tips {
  width: 100%;
  color: #b8bac2;
  font-size: 14px;
  text-align: center;
  margin-top: 30rpx;
  margin-bottom: 30rpx;
}
</style>
